package org.embedchat.protocol.codec.common;

import org.embedchat.protocol.Constants;
import org.embedchat.protocol.codec.AbstractMessageEncoder;
import org.embedchat.protocol.message.AbstractMessage;
import org.embedchat.protocol.message.common.TextMessage;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;

import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@SuppressWarnings("unchecked")
public class TextMessageEncoder extends AbstractMessageEncoder {
	
    private static final Set TYPES;

    static {
        Set types = new HashSet();
        types.add(TextMessage.class);
        TYPES = Collections.unmodifiableSet(types);
    }

    public TextMessageEncoder() {
        super(Constants.TEXT_MESSAGE);
    }

    protected void encodeBody(IoSession session, AbstractMessage message,
                              ByteBuffer out) {
        TextMessage m = (TextMessage) message;
        DataOutputStream dos = null;
        try {
            dos = new DataOutputStream(out.asOutputStream());
            dos.writeInt(m.getUserId());
            dos.writeUTF(m.getMessageString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (dos != null) {
                try {
                    dos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public Set getMessageTypes() {
        return TYPES;
    }
}
